package com.example.exam1.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.exam1.entity.User;
import com.example.exam1.service.UserService;
import com.example.exam1.util.JsonUtils;
import com.example.exam1.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * @author wushuang
 * recorrected by Deepwind
 */

@WebServlet("/user/*")
public class UserController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");

        String uri = req.getRequestURI();
        switch (uri) {
            case "/user/register" -> {
                doRegister(req, resp);
            }
            case "/user/login" -> {
                doLogin(req, resp);
            }
            default -> {
            }
        }
    }

    /*
     * 注册接口
     */
    private void doRegister(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取参数
        JSONObject json = JsonUtils.getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");

        // 数据封装，并调用service层方法处理
        int res = new UserService().register(new User(username, password));

        // 返回结果
        switch (res) {
            case 0 -> ResponseUtils.gen500Response(resp, "注册失败");
            case -1 -> ResponseUtils.genSuccessResponse(resp, "用户名或密码为空", null);
            case -2 -> ResponseUtils.gen404Response(resp, "该用户名已注册");
            case 1 -> ResponseUtils.genSuccessResponse(resp, "注册成功", null);
            default -> {
            }
        }
    }

    /*
     * 登录接口
     */
    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = JsonUtils.getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");

        int res = new UserService().login(new User(username, password));

        switch (res) {
            case 0 -> ResponseUtils.gen500Response(resp, "登录失败");
            case -1 -> ResponseUtils.gen404Response(resp, "用户名或密码为空");
            case -2 -> ResponseUtils.gen404Response(resp, "该用户名不存在");
            case 1 -> {
                req.getSession().setAttribute("user",username);
                ResponseUtils.genSuccessResponse(resp, "登录成功", null);
            }
            default -> {
            }
        }
    }


}
